package com.example.socialapp.ui.notification

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Comment
import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.PersonAdd
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material3.Divider
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.absoluteValue
import kotlin.random.Random

/**
 * 通知界面
 *
 * @param onNavigateBack 返回上一界面回调
 * @param onNavigateToUserProfile 导航到用户资料界面回调
 * @param onNavigateToPostDetail 导航到动态详情界面回调
 * @param onNavigateToSettings 导航到设置界面回调
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotificationScreen(
    onNavigateBack: () -> Unit,
    onNavigateToUserProfile: (String) -> Unit = {},
    onNavigateToPostDetail: (String) -> Unit = {},
    onNavigateToSettings: () -> Unit = {}
) {
    var selectedTabIndex by remember { mutableIntStateOf(0) }
    val tabs = listOf("全部", "点赞", "评论", "关注", "系统")
    
    val notifications = remember { generateSampleNotifications(30) }
    var showMenu by remember { mutableStateOf(false) }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("通知") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = { onNavigateToSettings() }) {
                        Icon(
                            imageVector = Icons.Default.Settings,
                            contentDescription = "通知设置"
                        )
                    }
                    IconButton(onClick = { showMenu = true }) {
                        Icon(
                            imageVector = Icons.Default.MoreVert,
                            contentDescription = "更多选项"
                        )
                        
                        DropdownMenu(
                            expanded = showMenu,
                            onDismissRequest = { showMenu = false }
                        ) {
                            DropdownMenuItem(
                                text = { Text("全部标为已读") },
                                onClick = { 
                                    showMenu = false 
                                    /* 标记全部已读逻辑 */ 
                                },
                                leadingIcon = {
                                    Icon(
                                        imageVector = Icons.Default.CheckCircle,
                                        contentDescription = null
                                    )
                                }
                            )
                            DropdownMenuItem(
                                text = { Text("清除全部通知") },
                                onClick = { 
                                    showMenu = false 
                                    /* 清除全部通知逻辑 */ 
                                },
                                leadingIcon = {
                                    Icon(
                                        imageVector = Icons.Outlined.Delete,
                                        contentDescription = null
                                    )
                                }
                            )
                        }
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
        ) {
            // 标签栏
            TabRow(selectedTabIndex = selectedTabIndex) {
                tabs.forEachIndexed { index, title ->
                    Tab(
                        selected = selectedTabIndex == index,
                        onClick = { selectedTabIndex = index },
                        text = { Text(title) }
                    )
                }
            }
            
            // 通知列表
            val filteredNotifications = when (selectedTabIndex) {
                1 -> notifications.filter { it.type == NotificationType.LIKE }
                2 -> notifications.filter { it.type == NotificationType.COMMENT }
                3 -> notifications.filter { it.type == NotificationType.FOLLOW }
                4 -> notifications.filter { it.type == NotificationType.SYSTEM }
                else -> notifications
            }
            
            if (filteredNotifications.isEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "暂无通知",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
            } else {
                LazyColumn(
                    modifier = Modifier.fillMaxSize()
                ) {
                    items(filteredNotifications) { notification ->
                        NotificationItem(
                            notification = notification,
                            onUserClick = { onNavigateToUserProfile(notification.userId) },
                            onContentClick = {
                                when (notification.type) {
                                    NotificationType.LIKE, NotificationType.COMMENT -> 
                                        notification.contentId?.let { onNavigateToPostDetail(it) }
                                    NotificationType.FOLLOW -> 
                                        onNavigateToUserProfile(notification.userId)
                                    NotificationType.SYSTEM -> { /* 系统通知处理 */ }
                                }
                            },
                            onDeleteClick = { /* 删除通知逻辑 */ }
                        )
                        Divider()
                    }
                }
            }
        }
    }
}

/**
 * 单个通知项
 */
@Composable
fun NotificationItem(
    notification: Notification,
    onUserClick: () -> Unit,
    onContentClick: () -> Unit,
    onDeleteClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onContentClick)
            .padding(16.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 通知图标或用户头像
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(CircleShape)
                .background(
                    when (notification.type) {
                        NotificationType.SYSTEM -> MaterialTheme.colorScheme.primary
                        else -> getColorForName(notification.userName)
                    }
                )
                .clickable(onClick = onUserClick),
            contentAlignment = Alignment.Center
        ) {
            if (notification.type == NotificationType.SYSTEM) {
                Icon(
                    imageVector = Icons.Default.Settings,
                    contentDescription = null,
                    tint = Color.White,
                    modifier = Modifier.size(24.dp)
                )
            } else {
                val icon = when (notification.type) {
                    NotificationType.LIKE -> Icons.Default.Favorite
                    NotificationType.COMMENT -> Icons.Default.Comment
                    NotificationType.FOLLOW -> Icons.Default.PersonAdd
                    else -> Icons.Default.Person
                }
                
                if (notification.showTypeIcon) {
                    Icon(
                        imageVector = icon,
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                } else {
                    Text(
                        text = notification.userName.first().toString(),
                        style = MaterialTheme.typography.titleMedium,
                        color = Color.White
                    )
                }
            }
        }
        
        Spacer(modifier = Modifier.width(16.dp))
        
        // 通知内容
        Column(
            modifier = Modifier.weight(1f)
        ) {
            if (notification.type != NotificationType.SYSTEM) {
                Text(
                    text = notification.userName,
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Bold
                )
                
                Spacer(modifier = Modifier.height(4.dp))
            }
            
            Text(
                text = notification.content,
                style = MaterialTheme.typography.bodyMedium,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(4.dp))
            
            Text(
                text = notification.formattedTime,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.outline
            )
        }
        
        Spacer(modifier = Modifier.width(8.dp))
        
        // 操作按钮
        IconButton(
            onClick = onDeleteClick,
            modifier = Modifier.size(40.dp)
        ) {
            Icon(
                imageVector = Icons.Default.DeleteOutline,
                contentDescription = "删除通知",
                tint = MaterialTheme.colorScheme.outline
            )
        }
        
        // 未读指示器
        if (!notification.isRead) {
            Box(
                modifier = Modifier
                    .size(8.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primary)
            )
        }
    }
}

/**
 * 通知类型
 */
enum class NotificationType {
    LIKE,       // 点赞通知
    COMMENT,    // 评论通知
    FOLLOW,     // 关注通知
    SYSTEM      // 系统通知
}

/**
 * 通知数据类
 */
data class Notification(
    val id: String,
    val type: NotificationType,
    val userId: String,
    val userName: String,
    val content: String,
    val contentId: String? = null,
    val timestamp: Long,
    val isRead: Boolean,
    val showTypeIcon: Boolean = false
) {
    val formattedTime: String
        get() {
            val now = System.currentTimeMillis()
            val diff = now - timestamp
            
            return when {
                diff < 60 * 1000 -> "刚刚"
                diff < 60 * 60 * 1000 -> "${diff / (60 * 1000)}分钟前"
                diff < 24 * 60 * 60 * 1000 -> "${diff / (60 * 60 * 1000)}小时前"
                else -> {
                    val sdf = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
                    sdf.format(Date(timestamp))
                }
            }
        }
}

/**
 * 根据名称生成颜色
 */
private fun getColorForName(name: String): Color {
    val colors = listOf(
        Color(0xFF6200EA), // 深紫色
        Color(0xFF2962FF), // 深蓝色
        Color(0xFF00BFA5), // 青色
        Color(0xFFFFAB00), // 琥珀色
        Color(0xFFD50000)  // 红色
    )
    
    return colors[name.hashCode().mod(colors.size).absoluteValue]
}

/**
 * 生成示例通知列表
 */
private fun generateSampleNotifications(count: Int): List<Notification> {
    val random = Random
    val currentTime = System.currentTimeMillis()
    val hourInMillis = 60 * 60 * 1000L
    
    val userNames = listOf("张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十")
    
    val notificationTemplates = mapOf(
        NotificationType.LIKE to listOf(
            "赞了你的动态",
            "对你的照片点赞了",
            "赞了你的评论"
        ),
        NotificationType.COMMENT to listOf(
            "评论了你的动态：太棒了！",
            "回复了你的评论：我也这么认为",
            "在你的动态下发表了评论：分享一下经验吧"
        ),
        NotificationType.FOLLOW to listOf(
            "关注了你",
            "开始关注你了"
        ),
        NotificationType.SYSTEM to listOf(
            "欢迎使用社交应用，点击查看新手指南",
            "你的账号安全检查完成，一切正常",
            "系统维护通知：系统将于今晚22:00-23:00进行例行维护",
            "你有新的好友推荐，点击查看",
            "你的动态获得了热门推荐"
        )
    )
    
    return List(count) { index ->
        val type = when {
            index % 10 == 0 -> NotificationType.SYSTEM
            index % 3 == 0 -> NotificationType.LIKE
            index % 5 == 0 -> NotificationType.FOLLOW
            else -> NotificationType.COMMENT
        }
        
        val userName = if (type == NotificationType.SYSTEM) "系统通知" else userNames[random.nextInt(userNames.size)]
        val userId = "user-${userNames.indexOf(userName)}"
        val templates = notificationTemplates[type] ?: listOf("")
        val content = templates[random.nextInt(templates.size)]
        
        Notification(
            id = "notification-$index",
            type = type,
            userId = userId,
            userName = userName,
            content = content,
            contentId = if (type == NotificationType.SYSTEM || type == NotificationType.FOLLOW) null else "post-$index",
            timestamp = currentTime - random.nextLong(1, 72) * hourInMillis / random.nextInt(1, 12),
            isRead = random.nextBoolean(),
            showTypeIcon = type == NotificationType.SYSTEM || random.nextBoolean()
        )
    }
} 